package com.elinkway.infinitemovies.bigdata;

import android.content.Context;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Environment;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.util.DisplayMetrics;

import com.elinkway.infinitemovies.config.SettingManage;
import com.elinkway.infinitemovies.ui.activity.LoginActivity;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.security.Key;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.spec.AlgorithmParameterSpec;
import java.util.Random;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.crypto.Cipher;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import javax.crypto.spec.IvParameterSpec;

import static com.letv.datastatistics.util.DEs.byteToString;

public class BigDataUtils {

    public static final String ALGORITHM_DES = "DES/CBC/PKCS5Padding";

    public static String getUniqueId(Context context) {
        SharedPreferences sharedPreferences = context.getSharedPreferences(
                "auid", Context.MODE_PRIVATE); // 私有数据
        // LogUtil.e("auid", "get:"+sharedPreferences.getString("uniqueId",
        // ""));
        String ret = sharedPreferences.getString("uniqueId", "");
        return ret;
    }

    public static String getMac(Context context) {
        String mac = BigDataPreference.getInstance().getString(
                BigDataPreference.MAC);
        if (TextUtils.isEmpty(mac)) {
            mac = getMacAddress(context);
            BigDataPreference.getInstance().putString(BigDataPreference.MAC,
                    mac);
        }
        return mac;
    }

    public static String getAUID(Context context) {
        String auid = BigDataPreference.getInstance().getString(
                BigDataPreference.AUID);
        if (TextUtils.isEmpty(auid)) {
            auid = MD5Helper(getAuidOrignal(context));
            BigDataPreference.getInstance().putString(BigDataPreference.AUID,
                    auid);
        }
        return auid;
    }

    private static String getAuidOrignal(Context context) {
        StringBuilder sb = new StringBuilder();
        sb.append(getIMEI(context)).append(getIMSI(context))
                .append(getDeviceName()).append(getBrandName())
                .append(getMacAddress(context));
        return sb.toString();

    }

    public static String ranLong() {
        Random r = new Random();
        String strRand="";
        for (int i=0; i<12; i++){
            strRand+=r.nextInt(10);
        }
        return strRand;
    }

    public static String getUUID(Context context) {
        SharedPreferences sharedPreferences = context.getSharedPreferences(
                "auid", Context.MODE_PRIVATE); // 私有数据
        return sharedPreferences.getString("uuid", "");
    }

    public static String getIMEI(Context context) {
        try {
            String deviceId = ((TelephonyManager) context
                    .getSystemService(Context.TELEPHONY_SERVICE)).getDeviceId();
            if (null == deviceId || deviceId.length() <= 0) {
                return "";
            } else {
                return deviceId.replace(" ", "");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
    }

    public static String getIMSI(Context context) {
        String subscriberId = ((TelephonyManager) context
                .getSystemService(Context.TELEPHONY_SERVICE)).getSubscriberId();
        if (null == subscriberId || subscriberId.length() <= 0) {
            // subscriberId = Constant.uuid;
        } else {
            subscriberId.replace(" ", "");
            if (TextUtils.isEmpty(subscriberId)) {
                // subscriberId = Constant.uuid;
            }
        }

        return subscriberId;
    }

    private static String getMacAddress(Context context) {
        String macAddress = null;
        WifiInfo wifiInfo = ((WifiManager) context
                .getSystemService(Context.WIFI_SERVICE)).getConnectionInfo();
        if (wifiInfo != null) {
            macAddress = wifiInfo.getMacAddress();
            if (macAddress == null || macAddress.length() <= 0) {
                return "";
            } else {
                return macAddress;
            }
        } else {
            return "";
        }
    }

    public static String getOSVersion() {
        return android.os.Build.VERSION.RELEASE;
    }

    public static String getDeviceName() {
        return android.os.Build.MODEL;
    }

    public static String getBrandName() {
        return android.os.Build.BRAND;
    }

    public static int getIpAddress(Context context) {

        WifiManager wifiManager = (WifiManager) (context
                .getSystemService(Context.WIFI_SERVICE));
        if (!wifiManager.isWifiEnabled()) {
            wifiManager.setWifiEnabled(true);
        }
        WifiInfo wifiInfo = wifiManager.getConnectionInfo();
        return wifiInfo.getIpAddress();

    }

    public static String getVersion(Context context) {
        PackageManager packageManager = context.getPackageManager();
        PackageInfo packInfo;
        String version = "";
        try {
            packInfo = packageManager.getPackageInfo(context.getPackageName(),
                    0);
            version = packInfo.versionName;
        } catch (NameNotFoundException e) {
            e.printStackTrace();
        }
        return version;
    }

    public static String getAndroidId(Context context) {
        String androidid = android.provider.Settings.System.getString(context.getContentResolver(), "android_id");
        return androidid;
    }

    public static String getPackageName(Context context) {
        return context.getPackageName();
    }

    public static int getConnectionType(Context context) {
        int nType;
        ConnectivityManager connMgr = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
        if (networkInfo == null) {
            nType = -1;
        } else {
            nType = networkInfo.getType();
        }
        return nType;
    }

    public static String getResolution(Context context) {
        DisplayMetrics dm = context.getResources().getDisplayMetrics();
        int w_screen = dm.widthPixels;
        int h_screen = dm.heightPixels;
        return String.format("%d_%d", h_screen, w_screen);

    }

    public static String getNetType(Context context) {
        if (context == null)
            return "nont";
        ConnectivityManager connectivityManager = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();

        if (networkInfo != null && networkInfo.isAvailable()) {
            if (ConnectivityManager.TYPE_WIFI == networkInfo.getType()) {
                return "wifi";
            } else {
                TelephonyManager telephonyManager = (TelephonyManager) context
                        .getSystemService(Context.TELEPHONY_SERVICE);

                switch (telephonyManager.getNetworkType()) {
                    case TelephonyManager.NETWORK_TYPE_GPRS:
                    case TelephonyManager.NETWORK_TYPE_CDMA:
                    case TelephonyManager.NETWORK_TYPE_EDGE:
                        return "2g";
                    case TelephonyManager.NETWORK_TYPE_LTE:
                        return "4g";
                    default:
                        return "3g";
                }
            }
        } else {
            return "nont";
        }
    }

    public static String MD5Helper(String str) {
        try {
            MessageDigest messageDigest = MessageDigest.getInstance("MD5");
            messageDigest.reset();
            messageDigest.update(str.getBytes("UTF-8"));
            byte[] byteArray = messageDigest.digest();
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < byteArray.length; i++) {
                if (Integer.toHexString(0xFF & byteArray[i]).length() == 1) {
                    sb.append("0").append(
                            Integer.toHexString(0xFF & byteArray[i]));
                } else {
                    sb.append(Integer.toHexString(0xFF & byteArray[i]));
                }
            }
            return sb.toString();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        throw new RuntimeException("no device Id");
    }

    public static String getSSID(Context context) {
        String uuid = "";
        WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
        WifiInfo wifiInfo = wifiManager.getConnectionInfo();
        if (wifiInfo == null)
            uuid = "ssid";
        else
            uuid = wifiInfo.getSSID();
        return uuid;
    }

    private static String readFile(String pfile) {

        String str = "";

        String result = "";

        FileReader fr = null;

        BufferedReader localBufferedReader = null;

        try {

            fr = new FileReader(pfile);

            localBufferedReader = new BufferedReader(fr, 8192);

            while ((str = localBufferedReader.readLine()) != null) {

                result = str;

            }

        } catch (Exception e) {

        } finally {

            try {

                if (localBufferedReader != null) {

                    localBufferedReader.close();

                }

                if (fr != null) {

                    fr.close();

                }

            } catch (Exception e) {

            }

        }

        return result;

    }

    public static String getInstallid(Context context) {

        SharedPreferences prefs;

        SharedPreferences.Editor prefEditor;

        prefs = context.getSharedPreferences("agnes", Context.MODE_PRIVATE);

        prefEditor = prefs.edit();

        String installid = prefs.getString("installid", "");

        if (installid.isEmpty()) {

            //

            String FILE_NAME = ".agnes_installid";

            String pkname = context.getPackageName();

            String ver = "";

            PackageManager pm = context.getPackageManager();

            if (pm != null) {

                try {

                    ver = pm.getPackageInfo(pkname, 0).versionName;

                } catch (Exception ex) {

                }

            }

            String FILE_ANDROID = Environment.getExternalStoragePublicDirectory("Android") + File.separator + FILE_NAME+"_"+pkname+"_"+ver;

            installid = readFile(FILE_ANDROID);

            //write installid to external file

            if (installid.isEmpty()) {

                installid = UUID.randomUUID().toString().replace("-", "");

                try {

                    File file = new File(FILE_ANDROID);

                    FileWriter writer = new FileWriter(file);

                    writer.write(installid);

                    writer.flush();

                    writer.close();

                } catch (Exception e) {

                }

            } else {

            }

            prefEditor.putString("installid", installid);

            prefEditor.commit();

        } else {

        }

        return installid;
    }

    public static String getSerialNo() {

        String command = "getprop";
        BufferedReader stdInput = null;
        BufferedReader stdError = null;
        String serialno ="";
        try {
            String s = null;
            Process process = Runtime.getRuntime().exec(command);
            stdInput = new BufferedReader(new InputStreamReader(process.getInputStream(),"utf-8"));
            stdError = new BufferedReader(new InputStreamReader(process.getErrorStream(),"utf-8"));
            // if has not such permission or some other error occurs, return null
            if ((s = stdError.readLine()) != null) {
                return null;
            }
            String reg = "\\[(.+?)\\]: \\[(.+?)\\]";
            Pattern pat = Pattern.compile(reg);
            while ((s = stdInput.readLine()) != null) {
                // os version
                if (s.indexOf("ro.serialno") > -1) {
                    Matcher matcher = pat.matcher(s);
                    if (matcher.find()) {
                        serialno = matcher.group(2);
                    }
                    break;
                }
            }
        } catch (Exception e) {

        } finally {
            try {
                if (stdInput != null) {
                    stdInput.close();
                }
            } catch (Exception e) {

            }
            try {
                if (stdError != null) {
                    stdError.close();
                }
            } catch (Exception e) {

            }
        }
        return serialno;
    }

    public static String desEncode(String key, byte[] data) {
        try {
            DESKeySpec dks = new DESKeySpec(key.getBytes());
            SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
            // key的长度不能够小于8位字节
            Key secretKey = keyFactory.generateSecret(dks);
            Cipher cipher = Cipher.getInstance(ALGORITHM_DES);
            IvParameterSpec iv = new IvParameterSpec("12345678".getBytes());
            AlgorithmParameterSpec paramSpec = iv;
            cipher.init(Cipher.ENCRYPT_MODE, secretKey, paramSpec);
            byte[] bytes = cipher.doFinal(data);
            return byteToString(bytes);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    public static String isLoginUser() {
        String uid = getUserUid();
        if(TextUtils.isEmpty(uid)){
            return BigDataConstants.ILU_FALSE;
        }else{
            return BigDataConstants.ILU_TRUE;
        }
    }

    public static String getUserUid(){
        SharedPreferences loginSp = BigDataStats.getcontext().getSharedPreferences(SettingManage.LOGIN_INFO, Context.MODE_PRIVATE);
        String uid = loginSp.getString(LoginActivity.UID, "");
        return uid;
    }

}
